from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone

class AuthUser(models.Model):
    """用户认证模型"""
    user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='用户')
    nickname = models.CharField(max_length=50, verbose_name='昵称')
    avatar = models.URLField(max_length=255, null=True, blank=True, verbose_name='头像')
    phone = models.CharField(max_length=11, unique=True, verbose_name='手机号')
    is_vip = models.BooleanField(default=False, verbose_name='是否VIP')
    vip_expire_time = models.DateTimeField(null=True, blank=True, verbose_name='VIP到期时间')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        app_label = 'common'
        db_table = 'auth_user'
        verbose_name = '用户'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']

    def __str__(self):
        return self.nickname or self.user.username

    @property
    def is_active(self):
        """是否激活"""
        return self.user.is_active

    @property
    def is_vip_expired(self):
        """检查VIP是否过期"""
        if not self.is_vip or not self.vip_expire_time:
            return True
        return self.vip_expire_time < timezone.now()

    def extend_vip(self, days):
        """延长VIP时间"""
        if not self.is_vip:
            self.is_vip = True
            self.vip_expire_time = timezone.now()
        
        if self.vip_expire_time and self.vip_expire_time > timezone.now():
            self.vip_expire_time = self.vip_expire_time + timezone.timedelta(days=days)
        else:
            self.vip_expire_time = timezone.now() + timezone.timedelta(days=days)
        
        self.save() 